package Helpers
{
	import Components.Card;
	import Components.PostIt;
	import Components.TaskTab;
	import Components.DevWorkspace;
	
	import Model.Task;
	
	import flash.events.Event;
	import flash.geom.Point;
	
	import mx.core.UIComponent;
	import mx.events.MoveEvent;

	public class TaskLink extends UIComponent
	{
		public var workspace:DevWorkspace;
		
		public var taskTab:TaskTab;
		public var postIt:PostIt;
		
		protected var source:UIComponent;
		protected var dest:UIComponent;	
			
		protected override function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
		{
			super.updateDisplayList(unscaledWidth, unscaledHeight);
			
			if(!source || !dest)
				if(!Bind())
					return;
					
			graphics.clear();
			graphics.lineStyle(5, 0, 0.3);
			var point:Point = middleToLocal(source);
			graphics.moveTo(point.x, point.y);
			
			point = middleToLocal(dest);
			graphics.lineTo(point.x, point.y);
		}
		
		protected function Bind():Boolean
		{
			if(!workspace) return false;
			if(!postIt) return false;
			
			var card:Card = workspace.getCardForTask(postIt.task);
			if(!card) return false;
				
			var taskTab:TaskTab = card.taskRack.getTabForTask(postIt.task);
			if(!taskTab) return false;
			
			source = taskTab;
			dest = postIt;
			addMoveTrigger(postIt);
			addMoveTrigger(card);
						
			return true;
		}
		
		private function addMoveTrigger(trigger:UIComponent):void
		{
			trigger.addEventListener(MoveEvent.MOVE, function(evt:Event):void
			{
				invalidateDisplayList();
			});
		}
		
		private function middleToLocal(uic:UIComponent):Point
		{
			var point:Point = new Point(uic.width/2, uic.height/2);
			point = uic.localToGlobal(point);
			return UIComponent(parent).globalToContent(point);
		}
	}
}